package com.linkivr;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class DBManager {

	String driver;
	String url;
	String user;
	String passwd;
	Connection conn = null;
	Statement st;
	ResultSet rs = null;

	public DBManager() {
	}

	public DBManager(String driver, String url, String user, String passwd) throws Exception {
		connect(driver, url, user, passwd);
	}

	public boolean connect(String driver, String url, String user, String passwd) throws Exception {

		boolean result = false;
		this.driver = driver;
		this.url = url;
		this.user = user;
		this.passwd = passwd;

		Class.forName(driver).newInstance();
		conn = DriverManager.getConnection(url, user, passwd);
		// conn.setAutoCommit(false);//
		st = conn.createStatement();
		result = true;

		return result;
	}

	public ResultSet executeQuery(String sql) throws Exception {
		rs = null;
		boolean connres = true;

		if ((conn == null) || (conn.isClosed())) {
			connres = connect(driver, url, user, passwd);
		}
		if (connres) {
			rs = st.executeQuery(sql);
		}

		return rs;
	}

	public int executeUpdate(String sql) throws Exception {
		int res = 0;
		boolean connres = true;

		if ((conn == null) || (conn.isClosed())) {
			connres = connect(driver, url, user, passwd);
		}
		if (connres) {
			res = st.executeUpdate(sql);
			// conn.commit();

		}

		return res;
	}

	public void close() {
		try {
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			GL.logException(e);
		}
	}
}
